package handler

import (
	"gitee.com/sheldwu/httpdns/config"
	"gitee.com/sheldwu/httpdns/util"
	"io"
	"net/http"

	"gitee.com/sheldwu/httpdns/module"

	"encoding/json"
)

var params []interface{}

type responseT struct {
	Data   map[string]string `json:"data"`
	Msg    string            `json:"msg"`
	Status int               `json:"status"`
}

/*
type responseT struct {
	MqttList   []string `json:"mqtt_list"`
	HttpDnsList    []string            `json:"httpdns_list"`
	RetryInternal int               `json:"status"`
}
*/

func getUid2Idc(userID string) (idc string, ok bool) {

	idc, ok = module.GetUid2Idc(userID)
	return idc, ok
}

func saveUid2Idc(userID string, idc string) {
	module.SaveUid2Idc(userID, idc)
}

func getIdcDomainMap(idc string) (map[string]string, bool) {
	idcDomainMap, ok := config.Idc2DomainMap[idc]
	return idcDomainMap, ok
}

func App(w http.ResponseWriter, req *http.Request) {
	var res responseT
	var idc string
	var userID string
	var idcCached bool
	req.ParseForm()

	userIDs, hasUserId := req.Form["user_id"]

	//glog.Info("hello, world")

	// 有 userID，试着从redis 取出userid 对应的idc关系
	if hasUserId {
		userID = userIDs[0]
		idc, idcCached = getUid2Idc(userID)
	}

	if !idcCached {
		ip := util.GetIp(req)
		idc, _ = util.GetIdcByIp(ip)
	}

	domainMap, ok := getIdcDomainMap(idc)
	if !ok {
		res.Status = 1
		res.Msg = "get domain map for idc:" + idc + " failed"
	} else {
		res.Status = 0
		res.Msg = "ok"
		res.Data = domainMap
		if hasUserId && !idcCached {
			saveUid2Idc(userID, idc)
		}
	}

	responseByte, _ := json.Marshal(&res)
	io.WriteString(w, string(responseByte))
	return
}
